package itsm.isperp.control.form.table.inspect;

import itsm.isperp.control.form.table.NormalTreeTable;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.module.entity.task.TskInspectTemplateCheck;
import itsm.isperp.module.entity.task.TskInspectTemplateCiCheck;
import itsm.isperp.module.service.task.TskInspectTemplateCheckService;
import itsm.isperp.module.service.task.TskInspectTemplateCiCheckService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.chanjar.weixin.common.util.StringUtils;

/**
 * 
 * 由多行所组成的表格
 * 
 * @author lizx
 * @date 2013-11-8
 * @since 1.0
 * 
 */
public class InspectTreeTable extends NormalTreeTable<InspectTreenodeRow> {

	String defId;

	String taskId;

	boolean readonly;

	public String getTaskId() {
		return taskId;
	}

	public void setTaskId(String taskId) {
		this.taskId = taskId;
	}

	public String getDefId() {
		return defId;
	}

	public void setDefId(String defId) {
		this.defId = defId;
	}

	public InspectTreeTable(String defId) {
		this.defId = defId;
	}

	public InspectTreeTable(String defId, String taskId, boolean readonly) {
		this.defId = defId;
		this.taskId = taskId;
		this.readonly = readonly;
	}

	/**
	 * 
	 * @param treenodeNamePath
	 * @param code
	 * @param calculateFormula
	 * @param value
	 */
	public void addRow(String id, String treenodeNamePath, String ciId,
			String ciName, String code, String value) {

		// 1、构建行，并比较当前cell的upon是否名称一样，如果是则upon的rowspan+1;
		// 2、构造到最后一列比较列总数与maxColumn只差，colSpan=maxColumn-size;
		// calculateFormula = calculateFormula.replace("%", "/100");
		int rowsSize = this.getRows().size();
		String[] nodes = treenodeNamePath.substring(1).split("/");

		// 取得最后一行作为上一行
		InspectTreenodeRow upRow = null;
		int upRowCellsLen = 0;
		if (rowsSize > 0) {
			upRow = this.getRows().get(rowsSize - 1);
			upRowCellsLen = upRow.getCells().size();
		}

		InspectTreenodeRow row = new InspectTreenodeRow();

		int nodesLen = nodes.length;

		if (upRowCellsLen < nodesLen && this.getMaxColumn() < nodesLen) {
			this.setMaxColumn(nodesLen);
		}

		for (int i = 0; i < nodesLen; i++) {
			String name = nodes[i];
			setRow(row, id, name, i, upRowCellsLen, rowsSize, upRow, ciId,
					ciName, code);
		}

		this.getRows().add(row);

	}

	private void setRow(InspectTreenodeRow row, String id, String name,
			int currentRowCellIndex, int upRowCellsLen, int rowsSize,
			InspectTreenodeRow upRow, String ciId, String ciName, String code) {
		InspectTreenodeCell newCell = new InspectTreenodeCell();

		if (currentRowCellIndex < upRowCellsLen) {
			InspectTreenodeCell upRowCell = upRow.getCells().get(
					currentRowCellIndex);
			// 如果需要合并必然不是最后的叶子节点
			if (name.equals(upRowCell.getName())) {
				if (upRowCell.getRowSpan() == 0) {
					upRowCell = findUpCell(upRowCell, rowsSize - 1,
							currentRowCellIndex);
				}

				upRowCell.setRowSpan(upRowCell.getRowSpan() + 1);
				newCell.setRowSpan(0);
			} else {
				// newCell.addCalculateFormula(calculateFormula, code);
			}
		} else {
			// newCell.addCalculateFormula(calculateFormula, code);
		}

		newCell.setCode(code);
		newCell.setName(name);
		newCell.setId(id);
		newCell.setCiId(ciId);

		newCell.setCiName(ciName);
		row.addCell(newCell);
	}

	/**
	 * 
	 * @param upRowCell
	 * @param lastIndex
	 * @param cellIndex
	 * @return
	 */
	private InspectTreenodeCell findUpCell(InspectTreenodeCell upRowCell,
			int lastIndex, int cellIndex) {
		InspectTreenodeRow row = this.getRows().get(lastIndex);
		InspectTreenodeCell cell = row.getCells().get(cellIndex);
		if (cell.getRowSpan() > 0) {
			return cell;
		}
		return findUpCell(upRowCell, lastIndex - 1, cellIndex);
	}

	public String renderHtmlWithValue() {
		// 输出为html
		StringBuilder sb = new StringBuilder();
		sb.append("<table id='template_table' class='template_table'><tr>");
		sb.append(
				"<th style='width:15%'>分类</th><th style='width:20%' colspan='")
				.append(this.getMaxColumn() - 1).append("'>").append("资产")
				.append("</th>");
		sb.append("<th style='width:120px'>");
		sb.append("巡检内容");
		sb.append("</th>");
		sb.append("<th style='width:200px'>巡检结果</th>");
		sb.append("<th>");
		sb.append("备注");
		sb.append("</th>");
		sb.append("</tr>");

		TskInspectTemplateCheckService tskInspectTemplateCheckService = ContextHolder
				.getSpringBean("tskInspectTemplateCheckService");

		List<TskInspectTemplateCheck> allChecks = tskInspectTemplateCheckService
				.findAllByDefId(defId);

		TskInspectTemplateCiCheckService tskInspectTemplateCiCheckService = ContextHolder
				.getSpringBean("tskInspectTemplateCiCheckService");

		List<TskInspectTemplateCiCheck> allChecksValue = tskInspectTemplateCiCheckService
				.findAllByTaskId(taskId);

		Map<String, TskInspectTemplateCiCheck> allChecksMap = new HashMap<>();

		for (TskInspectTemplateCiCheck ciCheck : allChecksValue) {
			allChecksMap.put(ciCheck.getTemplateCheckId(), ciCheck);
		}

		for (InspectTreenodeRow row : this.getRows()) {

			int size = row.getCells().size() - 1;

			sb.append("<tr>");

			for (int i = 0; i < size; i++) {
				InspectTreenodeCell cell = row.getCells().get(i);
				if (cell.getRowSpan() > 0) {
					sb.append("<td rowspan='" + cell.getRowSpan()
							+ "' data-code='" + cell.getCode() + "'>");
					sb.append(cell.getName());

					String cal = "0";

					sb.append("<input style='display:none' type='text' id='template_"
							+ cell.getCode()
							+ "' class='iscalculate' data-code='"
							+ cell.getCode()
							+ "'  data-calculate='"
							+ cal
							+ "'>");
					sb.append("</td>");
				}
			}

			InspectTreenodeCell cell = row.getCells().get(size);

			if (size + 1 < this.getMaxColumn()) {
				sb.append("<td rowspan='" + cell.getRowSpan() + "' colspan='"
						+ (this.getMaxColumn() - size) + "' data-code='"
						+ cell.getCode() + "'>");
			} else {
				sb.append("<td rowspan='" + cell.getRowSpan() + "' data-code='"
						+ cell.getCode() + "'>");
			}

			if (StringUtils.isNotEmpty(cell.getCiId())) {
				sb.append("<a class='nui-txt-link' href='javascript:openCiViewDialog(\""
						+ cell.getCiId() + "\")'>");
				sb.append(cell.getName());
				sb.append("(");
				sb.append(cell.getCode());
				sb.append(")");
				sb.append("</a>");
			} else {
				sb.append(cell.getName());
			}
			sb.append(" </td>");

			if (StringUtils.isNotEmpty(cell.getCiId())) {
				sb.append("<td colspan='3' class='td-item'>");
				sb.append("<table class='item-table'>");

				List<TskInspectTemplateCheck> checks = new ArrayList<>();
				for (TskInspectTemplateCheck c : allChecks) {
					if (c.getTemplateId().equals(cell.getId())) {
						checks.add(c);
					}
				}

				int csize = checks.size();
				for (int j = 0; j < csize; j++) {
					TskInspectTemplateCheck check = checks.get(j);

					if (csize == 1) {
						sb.append("<tr class='itemrowfl'>");
					} else {
						if (j == 0) {
							sb.append("<tr class='itemrowf'>");
						} else if (j == (csize - 1)) {
							sb.append("<tr class='itemrowl'>");
						} else {
							sb.append("<tr>");
						}
					}

					sb.append("<td class='itemcolf' style='width:120px'>");
					sb.append(check.getCheckName());
					sb.append("</td>");
					sb.append("<td style='width:200px'>");

					TskInspectTemplateCiCheck c = allChecksMap.get(check
							.getId());
					String cValue = "";
					if (c != null) {
						cValue = c.getCheckValue();
					}
					if (readonly) {
						if (StringUtils.isNotBlank(check.getDefaultValue())
								&& !check.getDefaultValue().equals(cValue)) {
							sb.append("<label class='item-unusual'>")
									.append(cValue).append("</label>");
						} else {
							sb.append(cValue);
						}

					} else {

						if ("checkbox".equals(check.getDataType())) {
							String itemStr = check.getItems();

							String[] items = itemStr.split("\\|");

							for (int ii = 0; ii < items.length; ii++) {

								if (cValue.equals(items[ii])) {
									sb.append("<input type='checkbox' id='c_"
											+ check.getId()
											+ "_"
											+ ii
											+ "' class='cbox_"
											+ check.getId()
											+ "'  name='ciCheckValues' checked='checked' value='"
											+ cValue + "'>");
								} else {
									if (items[ii].equals(check
											.getDefaultValue())) {
										sb.append("<input type='checkbox' id='c_"
												+ check.getId()
												+ "_"
												+ ii
												+ "' class='cbox_"
												+ check.getId()
												+ "'  name='ciCheckValues' checked='checked' value='"
												+ items[ii] + "'>");
									} else {
										sb.append("<input type='checkbox' id='c_"
												+ check.getId()
												+ "_"
												+ ii
												+ "' class='cbox_"
												+ check.getId()
												+ "'  name='ciCheckValues' value='"
												+ items[ii] + "'>");
									}
								}

								sb.append("<label for='c_" + check.getId()
										+ "_" + ii + "'>" + items[ii]
										+ "</label>");

								sb.append("</option >");
							}

						} else if ("select".equals(check.getDataType())) {
							String itemStr = check.getItems();
							sb.append("<select data-width='142px' id='c_"
									+ check.getId()
									+ "' name='ciCheckValues' value='" + cValue
									+ "' >");
							String[] items = itemStr.split("\\|");
							for (int ii = 0; ii < items.length; ii++) {

								if (cValue.equals(items[ii])) {
									sb.append("<option selected='selected'>");
								} else {
									if (items[ii].equals(check
											.getDefaultValue())) {
										sb.append("<option selected='selected'>");
									} else {
										sb.append("<option>");
									}
								}

								sb.append(items[ii]);

								sb.append("</option >");
							}

							sb.append("</select>");
						} else {
							sb.append("<input id='c_"
									+ check.getId()
									+ "' name='ciCheckValues' type='text' class='ci_check_value required "
									+ check.getDataType() + "' value='"
									+ cValue + "'>");

						}

					}

					if (readonly) {
						if (StringUtils.isNotEmpty(cValue)) {
							sb.append(check.getCheckUnit() == null ? "" : check
									.getCheckUnit());
						}
					} else {
						sb.append(check.getCheckUnit() == null ? "" : check
								.getCheckUnit());
					}

					sb.append("</td>");
					sb.append("<td class='itemcoll'>");

					if (readonly) {
						sb.append((c == null || c.getRemark() == null) ? "" : c
								.getRemark());
					} else {

						sb.append("<input type='hidden' id='ci_"
								+ check.getId()
								+ "' name='ciCheckCiIds' value='"
								+ check.getCiId() + "'>");
						sb.append("<input type='hidden' id='ct_"
								+ check.getId()
								+ "' name='templateCheckIds' value='"
								+ check.getId() + "'>");
						sb.append("<input type='text' id='r_"
								+ check.getId()
								+ "' name='ciCheckRemarks' class='check-remark' value='"
								+ ((c == null || c.getRemark() == null) ? ""
										: c.getRemark()) + "'>");
					}

					sb.append("</td>");
					sb.append("</tr>");
				}
				sb.append("</table>");
				sb.append(" </td>");
			}

			sb.append("</tr>");
		}
		sb.append("</table>");
		return sb.toString();

	}

	@Override
	public String renderHtml() {
		if (StringUtils.isNotBlank(taskId)) {
			return renderHtmlWithValue();
		}

		// 输出为html
		StringBuilder sb = new StringBuilder();
		sb.append("<table id='template_table' class='template_table'><tr>");
		sb.append(
				"<th style='width:15%'>分类</th><th style='width:20%' colspan='")
				.append(this.getMaxColumn() - 1).append("'>").append("资产")
				.append("</th>");
		sb.append("<th style='width:120px'>");
		sb.append("巡检内容");
		sb.append("</th>");
		sb.append("<th style='width:200px'>巡检结果</th>");
		sb.append("<th>");
		sb.append("备注");
		sb.append("</th>");
		sb.append("</tr>");

		TskInspectTemplateCheckService tskInspectTemplateCheckService = ContextHolder
				.getSpringBean("tskInspectTemplateCheckService");

		List<TskInspectTemplateCheck> allChecks = tskInspectTemplateCheckService
				.findAllByDefId(defId);

		for (InspectTreenodeRow row : this.getRows()) {

			int size = row.getCells().size() - 1;

			sb.append("<tr>");

			for (int i = 0; i < size; i++) {
				InspectTreenodeCell cell = row.getCells().get(i);
				if (cell.getRowSpan() > 0) {
					sb.append("<td rowspan='" + cell.getRowSpan()
							+ "' data-code='" + cell.getCode() + "'>");
					sb.append(cell.getName());

					String cal = "0";

					sb.append("<input style='display:none' type='text' id='template_"
							+ cell.getCode()
							+ "' class='iscalculate' data-code='"
							+ cell.getCode()
							+ "'  data-calculate='"
							+ cal
							+ "'>");
					sb.append("</td>");
				}
			}

			InspectTreenodeCell cell = row.getCells().get(size);

			if (size + 1 < this.getMaxColumn()) {
				sb.append("<td rowspan='" + cell.getRowSpan() + "' colspan='"
						+ (this.getMaxColumn() - size) + "' data-code='"
						+ cell.getCode() + "'>");
			} else {
				sb.append("<td rowspan='" + cell.getRowSpan() + "' data-code='"
						+ cell.getCode() + "'>");
			}

			if (StringUtils.isNotEmpty(cell.getCiId())) {
				sb.append("<a class='nui-txt-link' href='javascript:openCiViewDialog(\""
						+ cell.getCiId() + "\")'>");
				sb.append(cell.getName());
				sb.append("(");
				sb.append(cell.getCode());
				sb.append(")");
				sb.append("</a>");
			} else {
				sb.append(cell.getName());
			}
			sb.append(" </td>");

			if (StringUtils.isNotEmpty(cell.getCiId())) {
				sb.append("<td colspan='3' class='td-item'>");
				sb.append("<table class='item-table'>");

				List<TskInspectTemplateCheck> checks = new ArrayList<>();
				for (TskInspectTemplateCheck c : allChecks) {
					if (c.getTemplateId().equals(cell.getId())) {
						checks.add(c);
					}
				}

				int csize = checks.size();
				for (int j = 0; j < csize; j++) {
					TskInspectTemplateCheck check = checks.get(j);

					if (csize == 1) {
						sb.append("<tr class='itemrowfl'>");
					} else {
						if (j == 0) {
							sb.append("<tr class='itemrowf'>");
						} else if (j == (csize - 1)) {
							sb.append("<tr class='itemrowl'>");
						} else {
							sb.append("<tr>");
						}
					}

					sb.append("<td class='itemcolf' style='width:120px'>");
					sb.append(check.getCheckName());
					sb.append("</td>");
					sb.append("<td style='width:200px'>");

					if ("checkbox".equals(check.getDataType())) {
						String itemStr = check.getItems();

						String[] items = itemStr.split("\\|");

						for (int ii = 0; ii < items.length; ii++) {

							if (items[ii].equals(check.getDefaultValue())) {
								sb.append("<input type='checkbox' id='c_"
										+ check.getId()
										+ "_"
										+ ii
										+ "' class='cbox_"
										+ check.getId()
										+ "' name='ciCheckValues' checked='checked' value='"
										+ items[ii] + "'>");
							} else {
								sb.append("<input type='checkbox' id='c_"
										+ check.getId() + "_" + ii
										+ "' class='cbox_" + check.getId()
										+ "' name='ciCheckValues' value='"
										+ items[ii] + "'>");
							}
							sb.append("<label for='c_" + check.getId() + "_"
									+ ii + "'>" + items[ii] + "</label>");
						}

					} else if ("select".equals(check.getDataType())) {
						String itemStr = check.getItems();
						sb.append("<select data-width='142px' name='ciCheckValues' value='' >");
						String[] items = itemStr.split("\\|");
						for (int ii = 0; ii < items.length; ii++) {
							if (items[ii].equals(check.getDefaultValue())) {
								sb.append("<option selected='selected'>");
							} else {
								sb.append("<option>");
							}
							sb.append(items[ii]);
							sb.append("</option >");
						}

						sb.append("</select>");
					} else {
						sb.append("<input name='ciCheckValues' type='text' class='ci_check_value "
								+ check.getDataType() + "' value=''>");
					}
					sb.append(check.getCheckUnit() == null ? "" : check
							.getCheckUnit());

					sb.append("</td>");
					sb.append("<td class='itemcoll'>");
					sb.append("<input type='hidden' id='ci_" + check.getId()
							+ "' name='ciCheckCiIds' value='" + check.getCiId()
							+ "'>");
					sb.append("<input type='hidden' id='ct_" + check.getId()
							+ "' name='templateCheckIds' value='"
							+ check.getId() + "'>");
					sb.append("<input type='text' id='r_"
							+ check.getId()
							+ "' name='ciCheckRemarks' class='check-remark' value=''>");
					sb.append("</td>");
					sb.append("</tr>");

				}

				sb.append("</table>");
				sb.append(" </td>");
			}

			sb.append("</tr>");
		}
		sb.append("</table>");

		return sb.toString();
	}

	@Override
	public String renderHtml(boolean ifShowProceReady) {
		// TODO Auto-generated method stub
		return renderHtml();
	}
}
